import 'package:flutter/material.dart';
import 'package:qaun_ni_dev/utils/toast.dart';
import 'dart:convert';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:qaun_ni_dev/utils/request.dart';
import 'package:qaun_ni_dev/user_data.dart';


class RongImProvider with ChangeNotifier {

  // 融云的通讯录的id列表
  List conversionIdList = [];
  // 融云的会话列表
  List conList = new List();

  // 融云未读数
  int msgNoReadCount = 0;

  // 获取融云通讯录id列表
  getConversionUserIdList() async {
    List conversationList = await RongcloudImPlugin.getConversationList([
      RCConversationType.Private,
      RCConversationType.Group,
      RCConversationType.System
    ]);
    conversionIdList = [];
    for (Conversation con in conversationList) {
      conversionIdList.add(con.targetId.toString());
    }
    print('用户id列表>>>>${conversionIdList}');
    notifyListeners();
  }

  // 获取融云的会话列表
  Future getConversionList() async {
    print('获取会话列表执行了');
    List list = await RongcloudImPlugin.getConversationList(
        [RCConversationType.Private, RCConversationType.Group]);
    if (list != null) {
      list.sort((a, b) => b.sentTime.compareTo(a.sentTime));
      conList = list;
      getNoReadMsgCount();
    }
    notifyListeners();
  }

  // 获取融云token并初始化连接
  initImStateConnect(context) async{
    await requestPost(context, '/base/getCustomerAccount').then((value)async {
      var res = json.decode(value.toString());
      String rongCouldToken = res['msg'];
      RongcloudImPlugin.init(RongAppKey);
      if(rongCouldToken != null) {
        int rc = await RongcloudImPlugin.connect(rongCouldToken);
        print('融云connect result '+rc.toString());
      } else {
        Toast.toast(context,msg: '获取融云token失败了!');
      }

    });
    notifyListeners();
  }

  // 获取到全部的消息未读书
  getNoReadMsgCount () {
    RongcloudImPlugin.getTotalUnreadCount((int count, int code) {
      if( 0 == code) {
        print("所有的消息未读数为"+count.toString());
      }
      msgNoReadCount = count;
    });
    notifyListeners();
  }



}